package com.dylan.magic.guava.util;

import com.google.common.cache.CacheLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executor;
import java.util.function.Function;

/**
 * @author : ankang
 * @date : 2020/3/1 19:50
 * @Description :
 */
public class GuavaCacheUtil {
    private static Logger logger = LoggerFactory.getLogger(GuavaCacheUtil.class);

    private GuavaCacheUtil() {
    }

    /**
     * 创建同步CacheLoader
     *
     * @param function 通过key获取value的功能方法
     * @param <K>      key
     * @param <V>      value
     * @return CacheLoader
     */
    public static <K, V> CacheLoader<K, V> buildSyncCacheLoader(final Function<K, V> function) {
        return CacheLoader.from(key -> {
            logger.info("线程{}刷新缓存，key:{}", Thread.currentThread().getId(), key);
            try {
                return function.apply(key);
            } finally {
                logger.info("线程{}刷新缓存结束，key:{}", Thread.currentThread().getId(), key);
            }
        });
    }

    /**
     * 创建异步CacheLoader
     *
     * @param function 通过key获取value的功能方法
     * @param executor 线程执行器
     * @param <K>      key
     * @param <V>      value
     * @return CacheLoader
     */
    public static <K, V> CacheLoader<K, V> buildAsyncCacheLoader(final Function<K, V> function,
                                                                 final Executor executor) {
        return CacheLoader.asyncReloading(CacheLoader.from(key -> {
            logger.info("线程{}刷新缓存，key:{}", Thread.currentThread().getId(), key);
            try {
                return function.apply(key);
            } finally {
                logger.info("线程{}刷新缓存结束，key:{}", Thread.currentThread().getId(), key);
            }
        }), executor);
    }
}
